package com.ruoyi.common.utils.poi;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.exception.ServiceException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

/**
 * EasyExcel 导出工具类
 */
public final class EasyExcelUtils {

    private EasyExcelUtils() {
    }

    /**
     * 使用实体类头导出数据
     *
     * @param response 响应对象
     * @param fileName 文件名（不含扩展名）
     * @param sheetName 工作表名称
     * @param head 头定义 class
     * @param data 数据集
     * @param <T> 数据类型
     */
    public static <T> void write(HttpServletResponse response,
                                 String fileName,
                                 String sheetName,
                                 Class<T> head,
                                 List<T> data) {
        try {
            applyHeaders(response, fileName);
            EasyExcel.write(response.getOutputStream(), head)
                .autoCloseStream(Boolean.FALSE)
                .sheet(sheetName)
                .doWrite(data);
        } catch (IOException ex) {
            throw new ServiceException("导出Excel失败，请稍后重试", ex.hashCode());
        }
    }

    /**
     * 使用自定义头导出数据
     *
     * @param response 响应对象
     * @param fileName 文件名（不含扩展名）
     * @param sheetName 工作表名称
     * @param head 头部定义
     * @param data 数据集
     */
    public static void write(HttpServletResponse response,
                             String fileName,
                             String sheetName,
                             List<List<String>> head,
                             List<List<Object>> data) {
        try {
            applyHeaders(response, fileName);
            EasyExcel.write(response.getOutputStream())
                .autoCloseStream(Boolean.FALSE)
                .head(head)
                .sheet(sheetName)
                .doWrite(data);
        } catch (IOException ex) {
            throw new ServiceException("导出Excel失败，请稍后重试", ex.hashCode());
        }
    }

    private static void applyHeaders(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
            .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".xlsx");
    }
}
